<template>
  <el-card style="height: 80px">
    <el-form :inline="true" class="form">
      <el-form-item label="角色名称:">
        <el-input placeholder="请输入角色名称"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button>搜索</el-button>
        <el-button @click="resetting">重置</el-button>
      </el-form-item>
    </el-form>
  </el-card>
  <el-card>
    <el-button icon="Plus" style="margin-bottom: 10px" @click="addUser">
      添加角色
    </el-button>
    <el-table :data="tableList" border :fit="false" style="margin-bottom: 10px">
      <el-table-column
        label="#"
        min-width="50px"
        align="center"
        type="index"
      ></el-table-column>
      <el-table-column
        label="id"
        min-width="100px"
        align="center"
        prop="id"
      ></el-table-column>
      <el-table-column
        label="角色名称"
        min-width="150px"
        prop="roleName"
      ></el-table-column>
      <el-table-column
        label="创建时间"
        min-width="200px"
        prop="createTime"
      ></el-table-column>
      <el-table-column
        label="更新时间"
        min-width="200px"
        prop="updateTime"
      ></el-table-column>
      <el-table-column label="操作" min-width="350px">
        <template #default="{ row }">
          <el-button icon="User" @click="allocation(row)">分配权限</el-button>
          <el-button icon="Edit" @click="editUser(row)">编辑</el-button>
          <el-popconfirm title="是否删除" @confirm="roleDel(row)">
            <template #reference>
              <el-button icon="Delete">删除</el-button>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <Pagination
      v-model:page="currentPage"
      v-model:size="pageSize"
      :total="total"
      :background="true"
      @pagination="list"
      @paginations="paginations"
    ></Pagination>
  </el-card>
  <el-dialog
    v-model="dialog"
    width="700"
    :title="roleParams.id ? '修改职位' : '添加职位'"
  >
    <el-form :model="roleParams" :rules="rules" ref="form">
      <el-form-item label="职位名称" prop="roleName">
        <el-input
          placeholder="请输入职位名称"
          v-model="roleParams.roleName"
        ></el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="dialogCancel">取消</el-button>
      <el-button @click="save">确定</el-button>
    </template>
  </el-dialog>
  <!-- 抽屉 -->
  <el-drawer v-model="drawer" title="分配权限">
    <template #default>
      <el-tree
        ref="tree"
        :data="userMenuList"
        show-checkbox
        node-key="id"
        default-expand-all
        :default-checked-keys="menuArr"
        :props="defaultProps"
      />
    </template>
    <template #footer>
      <div style="display: flex; justify-content: end">
        <el-button @click="drawer = false">取消</el-button>
        <el-button @click="handler">确定</el-button>
      </div>
    </template>
  </el-drawer>
</template>
<script lang="ts" setup>
import { ref, onMounted, reactive, nextTick } from 'vue'
import {
  reqAllRoleList,
  reqAddOrUpdateRole,
  reqAllMenuList,
  reqSetPermisstion,
  reqDelect,
} from '@/api/acl/role/index'
import type {
  userList,
  recordsArray,
  succCode,
  userMenu,
  userMenuData,
} from '@/api/acl/role/type.ts'
import Pagination from '@/components/pagination/index.vue'
import { ElMessage, FormRules } from 'element-plus'
// 分页响应式数据
let currentPage = ref<number>(1)
let pageSize = ref<number>(8)
let total = ref<number>(0)
// table数据存储
let tableList = ref<recordsArray[]>()
// 控制el-dialog
let dialog = ref<boolean>(false)
// 新增修改form数据
let roleParams = reactive<recordsArray>({
  roleName: '',
})
// form表单ref
let form = ref<any>()
// 权限数据
let userMenuList = ref<userMenuData[]>([])
// 存储勾选节点的ID
let menuArr = ref<number[]>([])
// tree树形prop
const defaultProps = {
  children: 'children',
  label: 'name',
}
// tree实例
const tree = ref<any>()
// 抽屉
let drawer = ref<boolean>(false)
// form校验
const validateRoleName = (rule: any, value: any, callback: any) => {
  if (value.trim().length >= 2) {
    callback()
  } else {
    callback(new Error('职位名称最少两位'))
  }
}
let rules = reactive<FormRules<any>>({
  roleName: [
    {
      required: true,
      trigger: 'blur',
      validator: validateRoleName,
    },
  ],
})
// 初始化
const list = async () => {
  if (tableList.value?.length == 0) {
    currentPage.value -= 1
  }
  let res: userList = await reqAllRoleList(currentPage.value, pageSize.value)
  tableList.value = res.data.records
  total.value = res.data.total
}
onMounted(() => {
  list()
})
// 分页paginations
const paginations = () => {
  currentPage.value = 1
  list()
}
// 添加职位
const addUser = () => {
  dialog.value = true
  Object.assign(roleParams, {
    roleName: '',
    id: 0,
  })
  nextTick(() => {
    form.value.clearValidate('roleName')
  })
}
// 编辑职位
const editUser = (val: recordsArray) => {
  dialog.value = true
  Object.assign(roleParams, JSON.parse(JSON.stringify(val)))
  nextTick(() => {
    form.value.clearValidate('roleName')
  })
}
// 取消dialog
const dialogCancel = () => {
  dialog.value = false
}
// 确定
const save = async () => {
  await form.value.validate()
  let res: succCode = await reqAddOrUpdateRole(roleParams)
  if (res.code == 200) {
    ElMessage.success(roleParams.id ? '更新成功' : '添加成功')
    if (roleParams.id) {
      currentPage.value = 1
    }
    list()
    dialog.value = false
  } else {
    ElMessage.error(roleParams.id ? '更新失败' : '添加失败')
  }
}
// 分配权限
const allocation = async (val: recordsArray) => {
  Object.assign(roleParams, JSON.parse(JSON.stringify(val)))
  let res: userMenu = await reqAllMenuList(val.id as number)
  if (res.code == 200) {
    userMenuList.value = res.data
    menuArr.value = filterSelectArr(userMenuList.value, [])
    drawer.value = true
  } else {
    ElMessage.error(res.message)
  }
}
const filterSelectArr = (val: any, init: any) => {
  val.forEach((item: any) => {
    if (item.select && item.level == 4) {
      init.push(item.id)
    }
    if (item.children && item.children.length > 0) {
      filterSelectArr(item.children, init)
    }
  })
  return init
}
// 权限确定
const handler = async () => {
  const roleId = roleParams.id as number
  // 选中节点的ID
  let arr = tree.value.getCheckedKeys()
  // 半选的id
  let arr1 = tree.value.getHalfCheckedKeys()
  let permissionId = arr.concat(arr1)
  let res: succCode = await reqSetPermisstion(roleId, permissionId)
  if (res.code == 200) {
    drawer.value = false
    ElMessage.success('分配成功')
    window.location.reload()
  } else {
    ElMessage.error(res.message)
  }
}
const roleDel = async (val: recordsArray) => {
  let res = await reqDelect(val.id as number)
  if (res.code == 200) {
    ElMessage.success('删除成功')
    list()
  } else {
    ElMessage.error('删除失败')
  }
}
</script>
<style lang="scss" scoped>
.form {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>
